<!DOCTYPE html>
<html lang="zh-CN">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>博客编辑器</title>
  <link href="https://cdn.bootcdn.net/ajax/libs/normalize/8.0.1/normalize.min.css" rel="stylesheet">
  <link href="https://unpkg.com/@wangeditor/editor@latest/dist/css/style.css" rel="stylesheet">
  <style>
    :root {
      --primary-color: #1890ff;
      --success-color: #52c41a;
      --warning-color: #faad14;
      --error-color: #ff4d4f;
      --border-color: #e8e8e8;
      --bg-color: #f5f5f5;
      --text-color: #333;
      --text-secondary: #666;
      --shadow: 0 2px 10px rgb(0 0 0 / 12%);
    }

    * {
      box-sizing: border-box;
      margin: 0;
      padding: 0;
    }

    html, body {
      background-color: #fff;
      height: 100%;
      overflow: hidden;
      color: var(--text-color);
      font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
      line-height: 1.6;
    }

    #top-container {
      border-bottom: 1px solid var(--border-color);
      padding: 10px 30px;
      background-color: var(--bg-color);
    }

    #editor-toolbar {
      width: 1200px;
      max-width: 95%;
      background-color: #FCFCFC;
      margin: 0 auto;
      border-bottom: 1px solid var(--border-color);
    }

    #content {
      height: calc(100% - 120px);
      background-color: var(--bg-color);
      overflow-y: auto;
      position: relative;
    }

    #editor-container {
      width: 900px;
      max-width: 95%;
      margin: 30px auto 50px;
      background-color: #fff;
      padding: 40px 60px 60px;
      border: 1px solid var(--border-color);
      box-shadow: var(--shadow);
      border-radius: 8px;
    }

    #title-container {
      padding: 20px 0;
      border-bottom: 1px solid var(--border-color);
      margin-bottom: 30px;
    }

    #title-container input {
      font-size: 32px;
      border: 0;
      outline: none;
      width: 100%;
      line-height: 1.2;
      font-weight: 600;
      color: #1a1a1a;
      background: transparent;
    }

    #editor-text-area {
      min-height: 500px;
      margin-top: 20px;
    }

    /* 博客信息表单 */
    .blog-info-form {
      background: #f8f9fa;
      padding: 25px;
      border-radius: 8px;
      margin: 30px 0;
      border: 1px solid var(--border-color);
    }

    .form-group {
      margin-bottom: 20px;
    }

    .form-group label {
      display: block;
      margin-bottom: 8px;
      font-weight: 600;
      color: var(--text-color);
    }

    .form-group input,
    .form-group select {
      width: 100%;
      padding: 10px 12px;
      border: 1px solid #ddd;
      border-radius: 4px;
      font-size: 14px;
      transition: all 0.2s ease;
    }

    .form-group input:focus,
    .form-group select:focus {
      outline: none;
      border-color: var(--primary-color);
      box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.2);
    }

    /* 翻译设置 */
    .translation-section {
      background: #fff8e1;
      padding: 25px;
      border-radius: 8px;
      margin: 30px 0;
      border: 1px solid #ffd54f;
    }

    .language-grid {
      display: grid;
      grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
      gap: 15px;
      margin-top: 15px;
    }

    .language-option {
      display: flex;
      align-items: center;
      padding: 10px;
      background: white;
      border: 1px solid var(--border-color);
      border-radius: 4px;
      cursor: pointer;
      transition: all 0.2s ease;
    }

    .language-option:hover {
      border-color: var(--primary-color);
      background: #f0f8ff;
    }

    .language-option input {
      margin-right: 10px;
    }

    /* 操作按钮 */
    .action-buttons {
      display: flex;
      gap: 15px;
      margin-top: 30px;
      padding-top: 20px;
      border-top: 1px solid var(--border-color);
      flex-wrap: wrap;
    }

    .btn {
      padding: 12px 24px;
      border: none;
      border-radius: 6px;
      font-size: 14px;
      font-weight: 600;
      cursor: pointer;
      transition: all 0.2s ease;
      min-width: 120px;
    }

    .btn-primary {
      background: var(--primary-color);
      color: white;
    }

    .btn-primary:hover {
      background: #40a9ff;
      transform: translateY(-1px);
    }

    .btn-secondary {
      background: var(--bg-color);
      color: var(--text-secondary);
      border: 1px solid #ddd;
    }

    .btn-secondary:hover {
      background: #e8e8e8;
    }

    .btn-success {
      background: var(--success-color);
      color: white;
    }

    .btn-success:hover {
      background: #73d13d;
    }

    /* 选择控制按钮 */
    .selection-controls {
      display: flex;
      gap: 10px;
    }

    .btn-select-all,
    .btn-deselect-all {
      padding: 6px 12px;
      border: 1px solid var(--border-color);
      border-radius: 4px;
      background: white;
      color: var(--text-color);
      font-size: 12px;
      cursor: pointer;
      transition: all 0.2s ease;
    }

    .btn-select-all:hover {
      background: var(--primary-color);
      color: white;
      border-color: var(--primary-color);
    }

    .btn-deselect-all:hover {
      background: var(--error-color);
      color: white;
      border-color: var(--error-color);
    }

    /* 语言选项样式优化 */
    .language-option {
      display: flex;
      align-items: center;
      padding: 12px;
      background: white;
      border: 1px solid var(--border-color);
      border-radius: 6px;
      cursor: pointer;
      transition: all 0.2s ease;
      position: relative;
    }

    .language-option:hover {
      border-color: var(--primary-color);
      background: #f0f8ff;
      transform: translateY(-1px);
      box-shadow: 0 2px 8px rgba(24, 144, 255, 0.1);
    }

    .language-option input {
      margin-right: 12px;
      transform: scale(1.2);
    }

    .language-flag {
      font-size: 18px;
      margin-right: 8px;
      width: 24px;
      text-align: center;
    }

    .language-name {
      font-weight: 500;
    }

    /* 已选中状态 */
    .language-option input:checked + .language-flag + .language-name {
      color: var(--primary-color);
      font-weight: 600;
    }

    .language-option input:checked ~ .language-flag {
      filter: brightness(1.2);
    }

    /* 响应式设计 */
    @media (max-width: 768px) {
      #editor-container {
        padding: 20px;
      }
      
      .language-grid {
        grid-template-columns: 1fr;
      }
      
      .action-buttons {
        justify-content: center;
      }
      
      .btn {
        flex: 1;
        min-width: auto;
      }
      
      .selection-controls {
        flex-direction: column;
        gap: 8px;
      }
      
      .btn-select-all,
      .btn-deselect-all {
        width: 100%;
      }
    }
  </style>
</head>

<body>
  <div id="top-container">
    <p>
      <a href="blog.html">&lt;&lt; 返回博客管理</a>
    </p>
  </div>
  <div style="border-bottom: 1px solid #e8e8e8;">
    <div id="editor-toolbar"></div>
  </div>
  <div id="content">
    <div id="editor-container">
      <!-- 标题区域 -->
      <div id="title-container">
        <input id="blog-title" placeholder="请输入博客标题...">
      </div>

      <!-- 富文本编辑器区域 -->
      <div id="editor-wrapper">
        <div id="toolbar-container"><!-- 工具栏 --></div>
        <div id="editor-text-area" style="height: 500px; border: 1px solid #e8e8e8; margin-top: 10px;"><!-- 编辑器 --></div>
      </div>
      <textarea id="content" name="content" style="display: none;" required></textarea>

      <!-- 博客信息表单 -->
      <div class="blog-info-form">
        <h3 style="margin-top: 0; color: #333;">博客信息</h3>
        
        <div class="form-group">
          <label for="blog-category">分类:</label>
          <select id="blog-category">
            <option value="technology">技术</option>
            <option value="life">生活</option>
            <option value="travel">旅行</option>
            <option value="education">教育</option>
            <option value="business">商业</option>
            <option value="entertainment">娱乐</option>
          </select>
        </div>

        <div class="form-group">
          <label for="blog-theme">主题:</label>
          <input type="text" id="blog-theme" placeholder="请输入博客主题...">
        </div>

        <div class="form-group">
          <label for="blog-keywords">关键词 (逗号分隔):</label>
          <input type="text" id="blog-keywords" placeholder="例如: JavaScript,前端开发,编程...">
        </div>
      </div>

      <!-- 翻译设置 -->
      <div class="translation-section">
        <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 15px;">
          <h3 style="margin: 0; color: #d48806;">多语言翻译</h3>
          <div class="selection-controls">
            <button type="button" class="btn-select-all" onclick="blogEditor?.selectAllLanguages()">全选</button>
            <button type="button" class="btn-deselect-all" onclick="blogEditor?.deselectAllLanguages()">取消全选</button>
          </div>
        </div>
        <p style="color: #666; margin-bottom: 15px;">选择要翻译的目标语言，系统将自动生成多语言版本</p>
        
        <div class="language-grid">
          <label class="language-option">
            <input type="checkbox" name="language" value="zh-CN" checked>
            <span class="language-flag">🇨🇳</span>
            <span class="language-name">简体中文</span>
          </label>
          <label class="language-option">
            <input type="checkbox" name="language" value="en">
            <span class="language-flag">🇺🇸</span>
            <span class="language-name">English</span>
          </label>
          <label class="language-option">
            <input type="checkbox" name="language" value="ja">
            <span class="language-flag">🇯🇵</span>
            <span class="language-name">日本語</span>
          </label>
          <label class="language-option">
            <input type="checkbox" name="language" value="ko">
            <span class="language-flag">🇰🇷</span>
            <span class="language-name">한국어</span>
          </label>
          <label class="language-option">
            <input type="checkbox" name="language" value="es">
            <span class="language-flag">🇪🇸</span>
            <span class="language-name">Español</span>
          </label>
          <label class="language-option">
            <input type="checkbox" name="language" value="fr">
            <span class="language-flag">🇫🇷</span>
            <span class="language-name">Français</span>
          </label>
          <label class="language-option">
            <input type="checkbox" name="language" value="de">
            <span class="language-flag">🇩🇪</span>
            <span class="language-name">Deutsch</span>
          </label>
          <label class="language-option">
            <input type="checkbox" name="language" value="ru">
            <span class="language-flag">🇷🇺</span>
            <span class="language-name">Русский</span>
          </label>
          <label class="language-option">
            <input type="checkbox" name="language" value="pt">
            <span class="language-flag">🇵🇹</span>
            <span class="language-name">Português</span>
          </label>
          <label class="language-option">
            <input type="checkbox" name="language" value="it">
            <span class="language-flag">🇮🇹</span>
            <span class="language-name">Italiano</span>
          </label>
          <label class="language-option">
            <input type="checkbox" name="language" value="ar">
            <span class="language-flag">🇸🇦</span>
            <span class="language-name">العربية</span>
          </label>
          <label class="language-option">
            <input type="checkbox" name="language" value="hi">
            <span class="language-flag">🇮🇳</span>
            <span class="language-name">हिन्दी</span>
          </label>
        </div>
        
        <div class="selected-count" style="margin-top: 15px; color: #666; font-size: 14px;">
          已选择 <span id="selected-languages-count">1</span> 种语言
        </div>
      </div>

      <!-- 操作按钮 -->
      <div class="action-buttons">
        <button class="btn btn-secondary" onclick="saveDraft()">保存草稿</button>
        <button class="btn btn-primary" onclick="previewBlog()">预览</button>
        <button class="btn btn-success" onclick="publishBlog()">发布博客</button>
      </div>
    </div>
  </div>

  <script src="https://unpkg.com/@wangeditor/editor@latest/dist/index.js"></script>
  <script>
    // 博客编辑器应用
    class BlogEditor {
      constructor() {
        this.E = window.wangEditor;
        this.editor = null;
        this.toolbar = null;
        this.init();
      }

      init() {
        this.setupLanguage();
        this.createEditor();
        this.bindEvents();
        this.autoFocusTitle();
      }

      setupLanguage() {
        if (this.E && this.E.i18nChangeLanguage) {
          this.E.i18nChangeLanguage('zh-CN');
        }
      }

      createEditor() {
        // 检查编辑器是否已经存在
        if (this.editor) {
          this.editor.destroy();
        }

        const editorConfig = {
          placeholder: '开始撰写您的博客内容...',
          scroll: false,
          MENU_CONF: {
            uploadImage: {
              server: 'http://localhost:3000/api/upload',
              fieldName: 'file',
              maxFileSize: 5 * 1024 * 1024,
              allowedFileTypes: ['image/jpeg', 'image/png', 'image/gif', 'image/webp'],
              base64LimitSize: 10 * 1024 * 1024,
              customInsert: this.handleImageUpload.bind(this),
              customError: this.handleUploadError.bind(this)
            },
            codeSelectLang: {
              codeLangs: [
                { text: 'JavaScript', value: 'javascript' },
                { text: 'HTML', value: 'html' },
                { text: 'CSS', value: 'css' },
                { text: 'Python', value: 'python' },
                { text: 'Java', value: 'java' },
                { text: 'C++', value: 'cpp' },
                { text: 'SQL', value: 'sql' },
                { text: 'JSON', value: 'json' },
                { text: 'XML', value: 'xml' }
              ]
            }
          },
          onChange: this.handleContentChange.bind(this)
        };

        try {
          this.editor = this.E.createEditor({
            selector: '#editor-text-area',
            html: '<p><br></p>',
            config: editorConfig,
            mode: 'default'
          });

          this.toolbar = this.E.createToolbar({
            editor: this.editor,
            selector: '#toolbar-container',
            config: {
              excludeKeys: 'fullScreen',
              toolbarKeys: [
                'headerSelect', 'blockquote', '|',
                'bold', 'underline', 'italic', 'color', 'bgColor', '|',
                'fontSize', 'fontFamily', 'lineHeight', '|',
                'bulletedList', 'numberedList', 'todo', '|',
                'emotion', 'insertLink', 'uploadImage', 'insertTable', 'codeBlock', '|',
                'undo', 'redo', '|', 'preview', 'fullScreen'
              ]
            },
            mode: 'default'
          });
        } catch (error) {
          console.error('编辑器初始化失败:', error);
          this.showMessage('富文本编辑器初始化失败，请刷新页面重试', 'error');
        }
      }

      bindEvents() {
        // 编辑器点击事件
        document.getElementById('editor-text-area').addEventListener('click', (e) => {
          if (e.target.id === 'editor-text-area') {
            this.editor.blur();
            this.editor.focus(true);
          }
        });

        // 语言选择变化事件
        document.querySelectorAll('input[name="language"]').forEach(checkbox => {
          checkbox.addEventListener('change', () => {
            this.updateSelectedCount();
          });
        });

        // 键盘快捷键
        document.addEventListener('keydown', (e) => {
          if (e.ctrlKey || e.metaKey) {
            switch(e.key) {
              case 's':
                e.preventDefault();
                this.saveDraft();
                break;
              case 'p':
                e.preventDefault();
                this.previewBlog();
                break;
            }
          }
        });
      }

      handleImageUpload(res, insertFn) {
        if (res.success && res.data) {
          insertFn(res.data.url, '', res.data.url);
        } else {
          this.showMessage('图片上传失败：' + (res.message || '未知错误'), 'error');
        }
      }

      handleUploadError(xhr, editor) {
        this.showMessage('上传失败，请检查网络连接或文件大小', 'error');
      }

      handleContentChange(editor) {
        // 可以在这里添加实时保存功能
        console.log('内容已更新');
      }

      showMessage(message, type = 'info') {
        const alert = document.createElement('div');
        alert.className = `alert alert-${type}`;
        alert.textContent = message;
        alert.style.cssText = `
          position: fixed;
          top: 20px;
          right: 20px;
          padding: 12px 20px;
          border-radius: 4px;
          color: white;
          z-index: 1000;
          background: ${type === 'error' ? '#ff4d4f' : '#1890ff'};
        `;
        document.body.appendChild(alert);
        setTimeout(() => alert.remove(), 3000);
      }

      validateForm() {
        const title = this.getElement('blog-title').value.trim();
        const content = this.editor.getHtml().trim();
        
        if (!title) {
          this.showMessage('请输入博客标题', 'error');
          return false;
        }
        
        if (!content || content === '<p><br></p>') {
          this.showMessage('请输入博客内容', 'error');
          return false;
        }
        
        return true;
      }

      getElement(id) {
        return document.getElementById(id);
      }

      getBlogData() {
        return {
          title: this.getElement('blog-title').value,
          category: this.getElement('blog-category').value,
          theme: this.getElement('blog-theme').value,
          keywords: this.getElement('blog-keywords').value,
          content: this.editor.getHtml(),
          createdAt: new Date().toISOString(),
          translations: this.getSelectedLanguages()
        };
      }

      getSelectedLanguages() {
        const checkboxes = document.querySelectorAll('input[name="language"]:checked');
        return Array.from(checkboxes).map(cb => cb.value);
      }

      selectAllLanguages() {
        const checkboxes = document.querySelectorAll('input[name="language"]');
        checkboxes.forEach(cb => cb.checked = true);
        this.updateSelectedCount();
        this.showMessage('已全选所有语言', 'success');
      }

      deselectAllLanguages() {
        const checkboxes = document.querySelectorAll('input[name="language"]');
        checkboxes.forEach(cb => cb.checked = false);
        this.updateSelectedCount();
        this.showMessage('已取消所有语言选择', 'info');
      }

      updateSelectedCount() {
        const count = this.getSelectedLanguages().length;
        const countElement = document.getElementById('selected-languages-count');
        if (countElement) {
          countElement.textContent = count;
        }
      }

      getCategoryName(category) {
        const categories = {
          'technology': '技术',
          'life': '生活',
          'travel': '旅行',
          'education': '教育',
          'business': '商业',
          'entertainment': '娱乐'
        };
        return categories[category] || category;
      }

      async saveBlogToServer(blogData, successMessage) {
        try {
          const response = await fetch('http://localhost:3000/api/articles', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify(blogData)
          });
          
          const result = await response.json();
          
          if (result.success) {
            this.showMessage(successMessage, 'success');
            if (blogData.status === 'published') {
              setTimeout(() => {
                window.location.href = 'blog.html';
              }, 1000);
            }
          } else {
            this.showMessage('操作失败：' + result.message, 'error');
          }
        } catch (error) {
          this.showMessage('网络错误，请检查服务器连接', 'error');
          console.error('保存失败：', error);
        }
      }

      saveDraft() {
        if (!this.validateForm()) return;
        
        const blogData = this.getBlogData();
        blogData.status = 'draft';
        this.saveBlogToServer(blogData, '草稿保存成功！');
      }

      previewBlog() {
        if (!this.validateForm()) return;
        
        const blogData = this.getBlogData();
        const previewWindow = window.open('', '_blank');
        
        previewWindow.document.write(`
          <!DOCTYPE html>
          <html lang="zh-CN">
          <head>
            <meta charset="UTF-8">
            <title>${blogData.title} - 预览</title>
            <style>
              body { 
                font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; 
                max-width: 800px; 
                margin: 0 auto; 
                padding: 40px 20px; 
                line-height: 1.8;
              }
              h1 { 
                color: #1a1a1a; 
                border-bottom: 2px solid #1890ff; 
                padding-bottom: 10px; 
                margin-bottom: 20px;
              }
              .blog-meta { 
                color: #666; 
                margin: 20px 0; 
                padding: 15px;
                background: #f5f5f5;
                border-radius: 4px;
              }
              .blog-content { 
                margin-top: 30px;
              }
              .blog-content img {
                max-width: 100%;
                height: auto;
              }
            </style>
          </head>
          <body>
            <h1>${blogData.title}</h1>
            <div class="blog-meta">
              <strong>分类:</strong> ${this.getCategoryName(blogData.category)} | 
              <strong>主题:</strong> ${blogData.theme} | 
              <strong>关键词:</strong> ${blogData.keywords}
            </div>
            <div class="blog-content">${blogData.content}</div>
          </body>
          </html>
        `);
      }

      publishBlog() {
        if (!this.validateForm()) return;
        
        const blogData = this.getBlogData();
        blogData.status = 'published';
        this.saveBlogToServer(blogData, '博客发布成功！');
      }

      autoFocusTitle() {
        this.getElement('blog-title').focus();
      }
    }

    // 初始化应用
    let blogEditor;
    document.addEventListener('DOMContentLoaded', () => {
      blogEditor = new BlogEditor();
    });

    // 全局函数供按钮调用
    function saveDraft() { blogEditor?.saveDraft(); }
    function previewBlog() { blogEditor?.previewBlog(); }
    function publishBlog() { blogEditor?.publishBlog(); }
  </script>
</body>

</html>